﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Http;
using static System.Net.Mime.MediaTypeNames;

namespace FileSC.NetLIB
{
    public class JsonContent : TouchSocket.Http.HttpContent
    {
        internal object o { get; set; }
        internal byte[] o_jsonstring { get; set; }
        public JsonContent() { }
        public JsonContent(object o)
        {
            Use(o);
        }
        public long ContentLength { get; internal set; }

        public void Use(object o)
        {
            this.o = o;
            o_jsonstring = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(o));
            this.ContentLength = o_jsonstring.Length; 
        }
        public void UseDict(Dictionary<string, object> dict)
        {
            Use((object)dict);
        }
        protected override bool OnBuildingContent<TByteBlock>(ref TByteBlock byteBlock)
        {
            return false;
        }
        protected override void OnBuildingHeader(IHttpHeader header)
        {
            header.Add(HttpHeaders.ContentLength, ContentLength.ToString());
            header.Add(HttpHeaders.ContentType, $"application/json; charset=utf-8"); 
        }

        protected override async Task WriteContent(Func<ReadOnlyMemory<byte>, Task> writeFunc, CancellationToken token)
        {
            await writeFunc.Invoke(o_jsonstring).ConfigureAwait(false);
        }
    }
}
